#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdbool.h>
#include "ringfifo.h"
#include "sample_comm.h"
#include "xiecc_rtmp.h"
#include "log.h"

extern void * SAMPLE_VENC_1080P_CLASSIC(void *p);

#define BUFFER_SIZE 128*1024

int main(int argc, char *argv[])
{
	pthread_t id;
	char serverStrBuf[100];
	int ret;
	struct ringbuf ringinfo;
	int ringbuflen=0;
		
	if (argc !=2 ) {
		RTMP_Log(RTMP_LOGWARNING, "Usage: rtmp serverip -eg<< rtmp 192.168.1.100 >> \n");
		return -1;
	}
	
	sprintf(serverStrBuf, "rtmp://%s/live",argv[1]);
	RTMP_Log(RTMP_LOGINFO, "[%s][%d][%s]Server=%s\\n", __FILE__, __LINE__, __func__, serverStrBuf);
	
	ret = rtmp_sender_alloc(serverStrBuf);
	if (ret == FALSE) {
		RTMP_Log(RTMP_LOGERROR, "[ERROR][%s][%d][%s] pRtmp Error\n", __FILE__, __LINE__, __func__);
		return -1;
	}
	
	if (rtmp_sender_start_publish() == FALSE) {
		RTMP_Log(RTMP_LOGERROR, "[ERROR][%s][%d][%s] connect fail\n", __FILE__, __LINE__, __func__);	
		return -1;
	}
	
	ringmalloc(BUFFER_SIZE);
#ifdef H264_VENC_SAVE
	int timeCount = 0;
	FILE* pFile = NULL;
	pFile = fopen("/mnt/st1.h264", "wb");
	if (pFile == NULL) {
		printf("[%s][%d][%s] fopen Error\n", __FILE__, __LINE__, __func__);	
		return 0;
	}
#endif
	//hisi
	pthread_create(&id,NULL,SAMPLE_VENC_1080P_CLASSIC,NULL);
	while (1) {
#ifdef H264_VENC_SAVE
		ringbuflen = ringget(&ringinfo);
		if (ringbuflen !=0) {
			ret = fwrite(ringinfo.buffer, sizeof(unsigned char), ringinfo.size, pFile);
			printf("ret=%d\n",ret);
		}
		if(timeCount >= 1500) {
			printf("over\n");
			fclose(pFile);
			return 0;
		}
		continue;
#endif	
		if (FALSE == RTMP264_Send(ringget)) {	
			RTMP_Log(RTMP_LOGWARNING,"[%s][%d][%s] RTMP264_Send return FALSE\n", __FILE__, __LINE__, __func__);	
		} else {
			RTMP_Log(RTMP_LOGWARNING,"over\n");
			return 0 ;
		}
		usleep(5000);
	}
	return 0;
}

